<template>
  <div class="hd history">
    <!-- <div class="hd mt10">
      <img src="../../assets/yzf_Bg.png">
    </div> -->

    <search-bar :menu="menu" :showsearch="false" :activeitem="activeitem"></search-bar>

    <div class="hd mt10">
      <div class="bg-white">
        <position style="padding:12px;width:auto;">
          <router-link to="/cloud">云诊室</router-link>
          &gt;
          <span class="last">云就诊</span>
           <select-role @btnclick="selectFamilyHandle" class="fr"></select-role>
        </position>

        <div class="clearfix main" style="padding:0;" v-if="lists.length!=0">
          <p class="arr_tips">
            <span>注：实际以医院的排队叫号为准，如已预约则根据预约时段插入队列</span>
          </p>
            <ul class="meetinginfo_list">
              <li v-for="(value,index) in lists">
                <p class="list_head">
                  <font color="#A09F9C">就诊人：</font>
                  <span>{{person.personName}}</span>
                </p>
                <div class="flex flex_between flex_vcenter">
                  <ul class="infolist">
                    <li >
                      <img src="../../assets/就诊科室.png" alt="">
                      <font color="#A09F9C">就诊科室：</font>
                      <span>{{value.deptName}}</span>
                    </li>
                    <li>
                      <img src="../../assets/医生.png" alt="">
                      <font color="#A09F9C">医&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;生：</font>
                      <span>{{value.doctorName}}</span>
                    </li>
                    <li>
                      <img src="../../assets/就诊时间.png" alt="">
                      <font color="#A09F9C">就诊时间：</font>
                      <span>{{value.workDate}} {{value.startDt.slice(11,16)}}-{{value.endDt.slice(11,16)}}</span>
                    </li>
                  </ul>
                  <div class="flex flex_between">
                    <span class="linebtn">当前叫号<font color="#B35942"><b>{{value.currentNumber}}</b></font>号</span>
                    <span class="linebtn">我排在<font color="#B35942"><b>{{value.lineNumber}}</b></font>号</span>
                  </div>
                </div>
              </li>
            </ul>
          </div>
          <div class="no-data" v-else>
            暂无数据
          </div>

       <div class="warn pd20">
        <ul>
          <li>
            <img src="../../assets/warn.png" alt="">
            <span>温馨提示</span>
          </li>
          <li>1、云候诊只展示今日待就诊记录，如您预约了明天及以后的云诊室，需在就诊当天才能查看排队信息，预约记录可通过云诊室的预约记录查看。</li>
          <li>2、视频之前，您将收到短信提醒或推送消息，您可点击短信中的链接打开我院应用，进入诊间，也可提前打开APP进入“云候诊功能”等待医生呼叫。</li>

        </ul>
				</div>

          <el-dialog :visible.sync="accept_dialog" size="tiny" :show-close="showclose">
            <div class="text_c">
              <img src="../../assets/nav-5.png" alt=""/>
              <p class="mt10"><b>{{currentmeet.doctorName}}</b>医生正在邀请<b>{{person.personName}}</b>进行视频就诊。。。</p>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="joinmeet()">接 受</el-button>
              <el-button @click="refuse()">拒 绝</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
  </div>
</template>

<script>
  import {commonAjax, APPOINT_DESCRIPTION, CLOUD_MENU, PLATFORM_PREFIX, ORG_ID} from '../../api/api'
  import Loading from '../../components/Loading'
  import Position from '../../components/Position'
  import LeftTime from '../../components/LeftTime'
  import SelectRole from '../../components/SelectRole'
  import SiderMenu from '../../components/SiderMenu'
  import SearchBar from '../../components/SearchBar'
  import protoCheck from '../../common/js/protocheck'
//  import axios from 'axios'
  import $ from 'jquery'

  export default {
    components: {Position, Loading, LeftTime, SelectRole, SiderMenu, SearchBar},
    data () {
      return {
        accept_dialog: false,
        showclose: false,
        menu: CLOUD_MENU,
        activeitem: 1,
        person: JSON.parse(localStorage.person),
        lists: [],
        APPOINT_DESCRIPTION: APPOINT_DESCRIPTION,
        currentmeet: {},
        base64EncodeChars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
        timer: null,
        confID: '',
        url: ''
      }
    },
    mounted () {
      document.body.scrollTop = 0
      this.getWaitList()
      let self = this
      this.timer = setInterval(function () {
        self.getWaitList()
      }, 5000)
    },
    beforeDestroy () {
      clearInterval(this.timer)
      this.timer = null
    },
    methods: {
      selectFamilyHandle (f) {
        this.person = f
        this.getWaitList(f.mpiId)
      },
      getWaitList (id) {
        let mpiId = id || this.person.mpiId
        commonAjax(
          [ORG_ID, mpiId],
          `${PLATFORM_PREFIX}.cloudClinicService`,
          'getWaitList'
        ).then(res => {
          if (res.data.code === 200) {
            this.lists = res.data.body
            for (let i = 0; i < this.lists.length; i++) {
              if (this.lists[i].lineNumber === this.lists[i].currentNumber && this.lists[i].visitingState === '1') {
                this.accept_dialog = true
                this.currentmeet = this.lists[i]
              } else {
                this.accept_dialog = false
              }
            }
          } else {

          }
        }).catch(res => {
          this.$message({
            message: '连接服务器失败',
            type: 'error'
          })
        })
      },
      executeAction (jsonTextBase64) {
        var theResult = -1
        $.ajax(
          {
            type: 'GET',
            url: 'http://127.0.0.1:17979/IMConf',
            data: 'URL=IMConf://' + jsonTextBase64 + '/',
            dataType: 'jsonp',
            jsonp: 'jsonpCallback',
            success: function (data) {
              theResult = 0
              if (data.result !== 0) {
                alert(data.message)
              }
            },
            error: function () {
              theResult = 0
              alert('ajax error!')
            }
          }
        )

        setTimeout(function () {
          if (theResult !== 0) {
            alert('客户端软件未安装或者被破坏！')
          }
        }, 500)
      },
      enter () {
        const mID = this.currentmeet.confID
        const url = this.base64encode(this.currentmeet.url)
        const href = `allcam://meeting/?mID=${mID}&url=${url}&a=join`
        protoCheck(href, function () {
          console.log('no client ! failed')
        }, function () {
          console.log('success')
          window.location.href = href
        })
      },
      DirectEnterConf () {
        var jsonText = this.getJsonTextDirectEnterConf('117.78.40.139', '17979',
          this.person.personName, this.currentmeet.confID)
        var jsonTextBase64 = this.base64encode(this.utf16to8(jsonText))
        this.executeAction(jsonTextBase64)
      },
      getJsonTextDirectEnterConf (serverAddress, serverPort, userNickname, confID) {
        var jsonText = '{' +
          '"Server": {' +
          '"Address": "' + serverAddress + '",' +
          '"Port": ' + serverPort +
          '},' +
          '"Action": {' +
          '"Name": "DirectEnterConf",' +
          '"Parameters": {' +
          '"UserName": "' + userNickname + '",' +
          '"ConfID": ' + confID +
          '}' +
          '}' +
          '}'
        console.log(JSON.stringify(jsonText))
        return jsonText
      },
      base64encode (str) {
        var out, i, len
        var c1, c2, c3

        len = str.length
        i = 0
        out = ''
        while (i < len) {
          c1 = str.charCodeAt(i++) & 0xff
          if (i === len) {
            out += this.base64EncodeChars.charAt(c1 >> 2)
            out += this.base64EncodeChars.charAt((c1 & 0x3) << 4)
            out += '=='
            break
          }
          c2 = str.charCodeAt(i++)
          if (i === len) {
            out += this.base64EncodeChars.charAt(c1 >> 2)
            out += this.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
            out += this.base64EncodeChars.charAt((c2 & 0xF) << 2)
            out += '='
            break
          }
          c3 = str.charCodeAt(i++)
          out += this.base64EncodeChars.charAt(c1 >> 2)
          out += this.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
          out += this.base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6))
          out += this.base64EncodeChars.charAt(c3 & 0x3F)
        }
        return out
      },
      utf16to8 (str) {
        var out, i, len, c

        out = ''
        len = str.length
        for (i = 0; i < len; i++) {
          c = str.charCodeAt(i)
          if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i)
          } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
          } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
          }
        }
        return out
      },
      joinmeet () {
        this.accept_dialog = false
        commonAjax(
          [ORG_ID, this.person.mpiId, this.currentmeet.localDeptId, this.currentmeet.localDoctorId, this.currentmeet.regId, 1],
          `${PLATFORM_PREFIX}.cloudClinicService`,
          'pentientReply'
        ).then(res => {
          if (res.data.code === 200) {
            // this.DirectEnterConf()
            this.enter()
          }
        }).catch(res => {
          alert('service busy')
        })
      },
      refuse () {
        this.accept_dialog = false
        commonAjax(
          [ORG_ID, this.person.mpiId, this.currentmeet.localDeptId, this.currentmeet.localDoctorId, this.currentmeet.regId, 2],
          `${PLATFORM_PREFIX}.cloudClinicService`,
          'pentientReply'
        ).then(res => {
          console.log(JSON.stringify(res))
        }).catch(res => {
          alert('service busy')
        })
      }
    }
  }
</script>

<style lang="less">
  .history{
    .my_appointment{
      position: relative;
      padding: 20px;
      &:hover{
        background: #fff;
        box-shadow: 1px 1px 1px rgba(0,0,0,.5)
      }
      border-top: 1px solid #FEF2E9;
    }
    .content .my_appointment img{
      vertical-align: middle;
    }
    .my_appointment .illness_name{
      height: 42px;
      line-height: 42px;
      margin:0 auto;
      border-bottom: 1px dashed #FEF2E9;
    }
    .my_appointment .illness_name span:nth-of-type(1){
      font-size: 14px;
      color: #666666;
    }
    .myappoint_ul .middle{
      overflow: hidden;
      margin-top: 10px;
      margin-left:20px;
    }
    .myappoint_ul .middle li{
      display: inline-block;
      width: 33%;
    }
    .myappoint_ul .top{
      margin-top: 20px;
      margin-left:20px;
    }
    .myappoint_ul .bottom{
      margin-left:20px;
      padding-bottom: 20px;
      margin-top: 10px;
    }
    .myappoint_ul .bottom span:nth-of-type(1){
      color: #999999;
    }

    .myappoint_ul .middle .name{
      display: inline-block;
    }

    .myappoint_ul .middle .right{
      width: 200px;
    }
    .myappoint_ul .middle .state span:nth-of-type(1){
      color: #666666;
    }
    .position_left_time{
      position: absolute;
      right: 60px;
      top: 70px;
    }
    .position_left_time span:nth-of-type(1){
      color: #ff9900;
    }
    .position_left_time span:nth-of-type(2){
      color: #993333;
    }
    .position_left_time div{
      width: 82px;
      line-height: 36px;
      text-align:center;
      background-color: rgb(146,59,29);
      border-radius: 4px;
      color: #ffffff;
      margin-left: 10px;
      cursor: pointer;
      &.cancel {
        background: #ccc;
        color:#fff;
      }
    }
    .border{
      height: 1px;
      background-color: #cccccc;
      margin:20px auto;
    }
    .warn{
      margin: 20px;
      li{
        color: #666666;
        margin-top: 10px;
      }
    }
  }
  .meeting_tips{
    float:right;
    color:#f35e0d;
  }
  .infobtn{
    float:right;
  }
  .infobtn span{
    color:white!important;
  }
  .arr_tips{
    text-align: center;
    color:#ac4b1c;
    padding:10px;
  }
  .meetinginfo_list>li{
    padding:10px 20px;
    border:1px solid #F8EEE9;
    background-color: #FFF8F2;
    margin:0 20px 20px 20px;
  }
  .list_head{
    border-bottom:1px solid #F8EEE9;
    padding-bottom:10px;
  }
  .fright{
    float:right
  }
  .text_c{
    text-align: center;
  }
  .linebtn{
    display:block;
    width:155px;
    height:37px;
    background-image:url("../../assets/num_bg.png");
    text-align: center;
    line-height: 37px;
    margin:0 10px;
  }
  .infolist>li{
    padding:8px;
  }
</style>
